"""领料出库单：
    1.单据上加客户    领料部门    领料人字段
    2.添加新的固定资产作业类型，目的位置为报废，源位置为真实库位
    3.不生成发票明细
    4.固定资产出库后生成资产卡片，资产类型在出库单选
    5.添加新的统计菜单"""

from datetime import datetime, timedelta, date
from collections import defaultdict
from math import ceil

from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_compare
from odoo.addons import decimal_precision as dp


class Picking(models.Model):
    _inherit = 'stock.picking'

    nd_asset_user_id = fields.Many2one('res.users', string="资产领用人")
    nd_asset_department_id = fields.Many2one('hr.department', string="领料部门")
    nd_asset_partner_id = fields.Many2one('res.partner', string="资产客户")
    nd_asset_category_id = fields.Many2one('account.asset.category', string="资产类别")

    def is_asset_pick(self, picking, test_out=False):
        picking.ensure_one()
        if test_out:
            assets = [self.env.ref('nd_assets.nd_assets_picking_out')]
        else:
            assets = [self.env.ref('nd_assets.nd_assets_picking_out'),
                      self.env.ref('nd_assets.nd_assets_picking_in')]
        return picking.picking_type_id in assets

    def check_nd_asset_cards(self):
        """查看资产卡片"""
        action = self.env.ref('account_asset.action_account_asset_asset_form').read()[0]
        action['domain'] = [('nd_picking_id', 'in', self.ids)]
        return action

    @api.multi
    def action_done(self):
        """创建不生成发票"""
        for pick in self:
            if self.is_asset_pick(pick):
                res = super(Picking, pick.with_context(no_pre_account_line=True)).action_done()
                if self.is_asset_pick(pick, test_out=True):
                    self.create_assets_card(pick)
            else:
                res = super(Picking, pick).action_done()

    @api.model
    def create_assets_card(self, pickings):
        """根据传入信息创建资产卡片"""
        datas = []
        for pick in pickings:
            for move in pick.move_lines:
                asset_category_id = pick.nd_asset_category_id
                date_done = pick.date_done
                try:
                    value_price = abs(move.value) / move.quantity_done
                except ZeroDivisionError:
                    value_price = 0
                for i in range(ceil(move.quantity_done)):
                    data = {
                        'name': move.product_id.name,
                        'category_id': asset_category_id.id,
                        'code': pick.name,
                        'date': date_done,
                        'nd_picking_id': pick.id,
                        'value': value_price,
                    }
                    datas.append(data)
        self.env['account.asset.asset'].sudo().create(datas)

    @api.multi
    def action_cancel(self):
        """取消不推送到WMS"""
        for pick in self:
            if self.is_asset_pick(pick):
                res = super(Picking, pick.with_context(no_sync=True)).action_cancel()
            else:
                res = super(Picking, pick).action_cancel()


class MoveLine(models.Model):
    _inherit = 'stock.move.line'

    nd_asset_user_id = fields.Many2one(related="picking_id.nd_asset_user_id", store=True, string="资产领用人")
    nd_asset_department_id = fields.Many2one(related="picking_id.nd_asset_department_id", store=True, string="领料部门")
    nd_asset_partner_id = fields.Many2one(related="picking_id.nd_asset_partner_id", store=True, string="资产客户")


class Assets(models.Model):
    _inherit = 'account.asset.asset'

    nd_picking_id = fields.Many2one('stock.picking', string="入库单")
    nd_accessory_product_ids = fields.One2many('nd.asset.accessory', 'asset_id', string="附属设备")
    nd_uom_id = fields.Many2one('uom.uom', string="单位")
    method = fields.Selection([('linear', '平均年限法'), ('degressive', 'Degressive')])
    store_location = fields.Char('存放位置')


class AssetsProducts(models.Model):
    _name = 'nd.asset.accessory'
    _description = '资产附属设备'

    @api.model
    def _get_user_currency(self):
        currency_id = self.env['res.users'].browse(self._uid).company_id.currency_id
        return currency_id or self.env.ref("base.CNY")

    asset_id = fields.Many2one('account.asset.asset', string="所属资产")
    asset_code = fields.Char('资产编码')
    product_code = fields.Char('设备编码', related="product_id.default_code", store=True)
    product_id = fields.Many2one('product.product', string="设备名称")
    product_size = fields.Char('规格型号', related="product_id.nd_size", store=True)
    uom_id = fields.Many2one('uom.uom', string="计量单位", related="product_id.uom_id", store=True)
    qty = fields.Float('数量')
    currency_id = fields.Many2one('res.currency', string='币种', required=True,
                                  default=lambda self: self._get_user_currency())
    amount = fields.Monetary('金额')



class AssetCateg(models.Model):
    _inherit = 'account.asset.category'

    method_time = fields.Selection([('number', '折旧期数'), ('end', 'Ending Date')])
    method = fields.Selection([('linear', '平均年限法'), ('degressive', 'Degressive')])



